from random import Random

from django.core.mail import send_mail

from Jv.settings import EMAIL_FROM
from my_apps.user.models import EmailPro


def random_str(randomlength=8):
    """字符串生成"""
    str = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        str += chars[random.randint(0, length)]
    return str  # 将拼接的字符串返回


def send_register_email(email, host, send_type='register', code=None, user_id=None):  # 类型为注册
    """接收两个参数，一个邮箱，另一个是发送类型，注册或忘记密码"""
    email_recode = EmailPro()
    if code:
        pass
    else:
        code = random_str(16)  # 生成16位的随机字符串
    if user_id:
        email_recode.user_id = user_id
    email_recode.code = code
    email_recode.email = email
    email_recode.send_type = send_type
    email_recode.save()

    email_title = 'django 测试'
    email_body = '这是一个django测试'

    if send_type == 'register':
        email_title = '注册激活链接'
        email_body = '请点击下方的链接激活你的账号： http://{host}/user/active/{code}'.format(host=host, code=code)
    elif send_type == 'bound':
        email_title = '绑定激活链接'
        email_body = '请点击下方的链接绑定你的账号： http://{host}/user/bound/{code}'.format(host=host, code=code)
    elif send_type == 'forget':
        email_title = '重置密码链接'
        email_body = '请点击下方的链接重置你账号的密码： http://{host}/user/forget?code={code}'.format(host=host, code=code)

    send_status = send_mail(email_title, email_body, EMAIL_FROM, [email], fail_silently=False)
    if send_status:
        pass
